package org.openmore.common.str;

import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class OpenMoreStriUtils {
    /**
     * 获取指定位数的的string随机数，随机范围为A-Z 2-9
     * @param length string的长度
     * @return 指定lenght的随机字符串
     */
    public static String randomString(int length){
        // 去掉I,O, 0, 1
        String str = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
        return randomString(str, length);
    }

    /**
     * 获取指定位数的的string随机数，随机范围为0-9
     * @param length string的长度
     * @return 指定lenght的随机字符串
     */
    public static String randomNumber(int length){
        // 去掉I,O, 0, 1
        String str = "0123456789012345678901234567890123456789";
        return randomString(str, length);
    }

    /**
     * 获得指定位数的随机数，随机数集合由string指定
     * @param string
     * @param length
     * @return
     */
    public static String randomString(String string, int length){
        Random random = new Random();
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int num = random.nextInt(string.length());
            buf.append(string.charAt(num));
        }
        return buf.toString();
    }

    /**
     * 下划线转驼峰
     */
    private static Pattern linePattern = Pattern.compile("_(\\w)");
    public static String lineToHump(String str) {
//        str = str.toLowerCase();
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /***
     * 驼峰命名转为下划线命名
     *
     * @param para 驼峰命名的字符串
     */

    public static String humpToUnderline(String para) {
        StringBuilder sb = new StringBuilder(para);
        int temp = 0;
        for (int i = 1; i < para.length(); i++) {
            if (Character.isUpperCase(para.charAt(i))) {
                sb.insert(i + temp, "_");
                temp += 1;
            }
        }
        return sb.toString().toLowerCase();
    }
}
